<script>
import { computed, defineComponent } from 'vue'
import { createNamespace, transformSize, transformStyleSize } from '../utils'
import { scrollViewProps, scrollViewEmits } from './helper'

export default defineComponent({
	name: createNamespace('ScrollView')[0],
	options: {
		// https://uniapp.dcloud.io/matter.html#mp
		virtualHost: true
	},
	props: scrollViewProps,
	emits: scrollViewEmits,
	setup(props) {
		const theStyle = computed(() => {
			const { customStyle, width, height, maxHeight, scrollX, enableFlex } = props
			let style = ''
			if (width) style += `width:${transformSize(width)};`
			if (height) style += `height:${transformSize(height)};`
			if (maxHeight) style += `max-height:${transformSize(maxHeight)};`
			if (scrollX) style += `white-space:nowrap;`
			if (enableFlex) style += 'display:flex;'
			return transformStyleSize(customStyle) + style
		})

		return { theStyle }
	}
})
</script>

<template>
	<div v-if="!scrollable && enableFlex" class="fan-scroll-view fan-scroll-view--flex" :style="theStyle">
		<slot />
	</div>
	<scroll-view v-else class="fan-scroll-view" :style="theStyle" :scroll-x="scrollX" :scroll-y="scrollY"
		:scroll-with-animation="scrollWithAnimation" :enable-back-to-top="enableBackToTop" :upper-threshold="upperThreshold"
		:lower-threshold="lowerThreshold" :scroll-top="scrollTop" :scroll-left="scrollLeft" :enable-flex="enableFlex"
		:show-scrollbar="false" @scroll="$emit('scroll', $event)" @scrolltolower="$emit('scrolltolower')"
		@scrolltoupper="$emit('scrolltoupper')">
		<div v-if="enableFlex && scrollX && scrollable" class="fan-scroll-view--flexin">
			<slot />
		</div>
		<slot v-else />
	</scroll-view>
</template>

<style lang="less">
.fan-scroll-view {
	-webkit-overflow-scrolling: touch;
	box-sizing: border-box;

	&--flex {
		display: flex;
	}

	// fix https://juejin.cn/post/7042879113127804941
	&--flexin {
		height: 100%;
		display: flex;
		flex-wrap: nowrap;
		width: max-content;
	}
}
</style>